/**
 * 
 */
package edu.sjtu.seda.main;

import java.util.ArrayList;
import java.util.List;

import edu.sjtu.seda.event.Event;
import edu.sjtu.seda.event.Event.STATUS;
import edu.sjtu.seda.stage.Stage;
import edu.sjtu.seda.stage.StageConfigLoader;
import edu.sjtu.seda.stage.StageImpl;
import edu.sjtu.seda.stage.api.StageConfig;

/**
 * @author john.zhu
 *
 */
public class StagePlatform {
	private List<Stage> stages = new ArrayList<Stage>();
	
	public StagePlatform(){
		init();
	}
	
	private void init(){
		buildStages();
	}
	
	public void buildStages(){
		List<StageConfig> configs = StageConfigLoader.getStageConfigList();
		if(configs!=null&&!configs.isEmpty()){
			for(StageConfig config : configs){
				List<Stage> st = new ArrayList<Stage>();
				if(stages!=null&&!stages.isEmpty()){
					for(Stage stage : stages){
						if(config.getStage().equals(stage.getName())){
							st.add(stage);
						}
					}
					stages.removeAll(st);
				}
				Stage stage = new StageImpl(config);
				stages.add(stage);
			}
		}
	}
	
	public List<Stage> getStageList(){
		return stages;
	}
	
	public Stage getStage(String name){
		if(stages!=null&&!stages.isEmpty()){
			for(Stage stage : stages){
				if(name.equals(stage.getName())){
					return stage;
				}
			}
		}
		return null;
	}
	
	public void start(){
		if(stages!=null&&!stages.isEmpty()){
			for(Stage stage : stages){
				stage.start();
			}
		}
	}
	
	public void pushEvent(Event event){
		event.setStatus(STATUS.START);
		Stage stage = event.nextLocation();
		if(stage!=null){
			stage.getStageWrapper().getEventQueue().pushEvent(event);
		}
	}
	
	public void destroy(){
		if(stages!=null&&!stages.isEmpty()){
			for(Stage stage : stages){
				stage.destroy();
			}
		}
	}

}
